package com.business.system.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.business.system.util.FileUtil;
import com.business.system.util.JCDateDeserializer;
import net.sf.rose.jdbc.DBUtils;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.StringUtil;
import net.sf.rose.web.utils.WebUtils;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.business.system.action.BaseAction;
import com.business.system.bean.*;
import com.business.system.util.DBTools;
import sun.misc.BASE64Decoder;

/**
 * @author: xudy
 * @date: 2018/04/12 8:56
 * @description:微信端申请模块API接口
 */
@RestController
@RequestMapping("api/apply")
public class ApiApplyAction extends BaseAction {
    /**
     * 根据用户和areaCode获取全部品牌(一个区域只能代理或者加盟一个品牌,不能出现一个区域可以同时既是代理商,又是加盟商的情况)
     * @param service
     * @param userId 用户id
     * @param areaCode 区域代码
     * @return
     */
	@RequestMapping("list.do")
	public List<BrandBean> list(Service service,String userId,String areaCode) {
	    //如果areaCode==null 获取全部品牌
	    //否则根据userId和areaCode获取对应区域还可以申请的品牌
        List<BrandBean> list = null;
	    if(areaCode==null){
            list = DBUtils.getBeanList(service, BrandBean.class);
        }else{
	        StringBuilder sql = new StringBuilder();
	        sql.append("select t1.* from BRAND t1 where t1.id not in");
	        sql.append(" (select t2.brand_id as id from user_brand t2 where t2.user_id=? and t2.area_code=?)");
            list = DBTools.getBeanList(service,BrandBean.class,sql.toString(),userId,areaCode);
        }
        return list;
	}

    /**
     * 获取二维码对应的用户信息
     * @param service
     * @param qrcode
     * @return
     */
    @RequestMapping("/getRecommendUser.do")
	public WxUserBean getRecommendUser(Service service,String qrcode){
	    Map<String,Object> params = new HashMap<>();
	    params.put("qrcode",qrcode);
	    WxUserBean userBean = DBUtils.getBean(service,WxUserBean.class,params);
	    return userBean;
    }

    /**
     * 提交申请(包括代理和加盟的接口)
     * @param service
     * @param request
     * @param json
     * @param brandIds
     * @return
     */
	@RequestMapping("saveApply.do")
	public boolean saveApply(Service service, HttpServletRequest request,String json,String brandIds,String userInfo) {
	    boolean status = false;
        ApplyBean apply = StringUtil.parse(json,ApplyBean.class);
        //提交申请时有些参数需要设置成默认状态
        //等待审核
        apply.setApplyStatus(1);
        //等待付款
        apply.setPayStatus(ApplyBean.PAY_NOT);
        int i = DBUtils.update(service,apply);
        if(i>0){
            List<UserBrandBean> list = new ArrayList<>();
            for(String id : brandIds.split(",")){
                UserBrandBean brand = new UserBrandBean();
                brand.setApplyId(apply.getId());
                brand.setAreaCode(apply.getAreaCode());
                brand.setArea(apply.getArea());
                brand.setBrandId(id);
                brand.setUserId(apply.getUserId());
                list.add(brand);
            }
            int [] result = DBTools.bacthInsertBean(service,UserBrandBean.class,list);
            if(result.length == brandIds.split(",").length){
                //更新用户信息
                ParserConfig jcParserConfig = new ParserConfig();
                jcParserConfig.putDeserializer(Date.class, JCDateDeserializer.instance);
                WxUserBean user = JSON.parseObject(userInfo, WxUserBean.class, jcParserConfig, JSON.DEFAULT_PARSER_FEATURE);
                DBUtils.update(service,user);
                status = true;
            }
        }
		return status;
	}

    /**
     * 获取最新的等待审核的记录(如果存在尚在审核或者等待支付的申请则需要完成之前的申请才能进行后面的申请)
     * 为空则可以继续申请其他的,否则不能申请
     * 提示当前的状态等待申请审核(APPLY_STATUS=1)
     * 提示当前的状态等待付款(APPLY_STATUS=2 && PAY_STATUS==1)
     * 提示当前的状态等待支付审核(APPLY_STATUS=2 && PAY_STATUS==2)
     * @param service
     * @param request
     * @return
     */
	@RequestMapping("getNewApply.do")
	public ApplyBean getNewApply(Service service,HttpServletRequest request){
	    Map<String,Object> param = WebUtils.getRequestData(request);
	    //等待申请审核 or 等待付款 or 等待支付审核
	    String sql = "select * from apply where user_id=? and type=? and (APPLY_STATUS=1 or PAY_STATUS<3)";
	    ApplyBean bean = DBTools.getBean(service,ApplyBean.class,sql,param.get("userId"),param.get("type"));
	    return bean;
    }

    /**
     * 线下打款的信息展示
     * @param request
     * @param service
     * @return
     */
    @RequestMapping(value = "/getPlatformInfo.do",method = RequestMethod.GET)
    public PlatformInfoBean getPlatformInfo(HttpServletRequest request, Service service){
        PlatformInfoBean info = DBTools.getBean(service,PlatformInfoBean.class,"select * from platform_info");
        return info;
    }

    /**
     * 上传凭证
     * @param request
     * @param service
     * @param applyId 申请id
     */
    @RequestMapping(value = "/uploadCreditImg.do",method = RequestMethod.POST)
    public boolean uploadCreditImg(HttpServletRequest request, Service service,String applyId,String base64){
        ApplyBean bean = DBUtils.getBean(service,ApplyBean.class,applyId);
        if(bean!=null){
            // 通过base64来转化图片
            base64 = base64.contains("base64")?base64.split("base64,")[1]:base64;
            BASE64Decoder decoder = new BASE64Decoder();
            // Base64解码
            byte[] imageByte = null;
            try {
                imageByte = decoder.decodeBuffer(base64);
                for (int i = 0; i < imageByte.length; ++i) {
                    if (imageByte[i] < 0) {// 调整异常数据
                        imageByte[i] += 256;
                    }
                }

                String ctxPath = FileUtil.getUploadFilePath();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
                String ymd = sdf.format(new Date());
                ctxPath += File.separator + ymd + File.separator;
                // 创建文件夹
                File file = new File(ctxPath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                UUID uuid = UUID.randomUUID();
                String path = ymd + "/" + uuid +".png";
                File uploadFile = new File(FileUtil.getUploadFilePath() + "/" +path);
                FileCopyUtils.copy(imageByte, uploadFile);
                ApplyFileBean fileBean = new ApplyFileBean();
                fileBean.setApplyId(applyId);
                fileBean.setFileName(uuid.toString());
                fileBean.setFilePath(path);
                fileBean.setType(bean.getType());
                if(DBUtils.update(service,fileBean)>0){
                    bean.setPayType(2);//凭证上传
                    bean.setPayStatus(ApplyBean.PAY_TO_CHECK);
                    return DBUtils.update(service,bean)>0;
                }


            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

}